package com.scau.phr.common.domain;

import com.scau.phr.common.exceptions.ErrorCode;

import java.util.HashMap;

/**
 * 统一的Json返回格式
 * @author yuzhiyi
 * @date 2018/7/9 10:51
 */
public class ApiResult {
    /**
     * 错误码，对应{@link ErrorCode}，表示一种错误类型
     * 如果是成功，则code为200
     */
    private int code;
    /**
     * 对错误的具体解释
     */
    private String message;
    /**
     * 返回的结果包装在value中，value可以是单个对象
     */
    private final Object value;

    private final static Object NULL_VALUE = new HashMap(0);
    public  static final Object DEFAULT_SUCCESS_RESULT = ApiResult.valueOf(NULL_VALUE);


    public ApiResult(int code,String message){
        this.code = code;
        this.message = message;
        this.value = NULL_VALUE;
    }

    public ApiResult(int code,String message,Object value){
        this.code = code;
        this.message = message;
        if (value == null){
            value = NULL_VALUE;
        }
        this.value = value;
    }

    public ApiResult(ErrorCode code,Object value){
        this.code = code.getCode();
        this.message = code.getMsg();
        this.value = value;
    }

    public static ApiResult valueOf(Object value){
        if (value instanceof ErrorCode){
            return new ApiResult(((ErrorCode) value).getCode(),"",null);
        }
        if (value == null){
            value = NULL_VALUE;
        }
        return new ApiResult(ErrorCode.SUCCESS.getCode(),"",value);
    }

    public static ApiResult errorOf(ErrorCode code,String message){
        return new ApiResult(code.getCode(),message,NULL_VALUE);
    }

    public static ApiResult errorOf(ErrorCode code){
        return new ApiResult(code.getCode(),"",NULL_VALUE);
    }

    public int getCode() {
        return code;
    }

    public String getMessage() {
        return message;
    }

    public Object getValue() {
        return value;
    }

    @Override
    public String toString() {
        return "ApiResult{" +
                "code=" + code +
                ", message='" + message + '\'' +
                ", value=" + value +
                '}';
    }

}
